#include "CodeBox.h"


CodeBox::CodeBox(std::string inFilename, float inPositionX, float inPositionY, std::vector<CodeElement> inElements): UIWidget(inFilename, inPositionX, inPositionY)
{
	float xOffset = 44.0f;
	active = false;
	hidden = false;
	for(int i = 0; i < 4; ++i)
	{
		if(i == 0)
		{
			xOffset = 44.0f;
		}
		else
		{
			xOffset = 44.0f;
		}

		switch (inElements[i])
		{
		case X_BUTTON: 
			{
				UIWidget* temp = new UIWidget("art/x_button.png", inPositionX + (xOffset*i) + 8, inPositionY + 32.0f);
				codeVector.push_back(temp);
			}
			break;
		case Y_BUTTON:
			{
				UIWidget* temp = new UIWidget("art/y_button.png", inPositionX + (xOffset*i) + 8, inPositionY + 32.0f);
				codeVector.push_back(temp);
			}
			break;
		case A_BUTTON:
			{
				UIWidget* temp = new UIWidget("art/a_button.png", inPositionX + (xOffset*i) + 8, inPositionY + 32.0f);
				codeVector.push_back(temp);
			}
			break;
		case B_BUTTON:
			{
				UIWidget* temp = new UIWidget("art/b_button.png", inPositionX + (xOffset*i) + 8, inPositionY + 32.0f);
				codeVector.push_back(temp);
			}
		}
	}

	flickerTex.loadFromFile("art/pda_filter.png");

	flickerSprite.setTexture(flickerTex);
	flickerSprite.setPosition(inPositionX + 8, inPositionY + 32.0f);

	flickered = 0;
}

void CodeBox::render(sf::RenderWindow* w)
{
	if(active && toRender)
	{
		for(int i = 0; i < 4; i++)
		{
			codeVector[i]->setActive();
		}
		UIWidget::render(w);

		for(int i = 0; i < 4; i++)
		{
			codeVector[i]->render(w);
		}

		w->draw(flickerSprite);
	}
}

void CodeBox::flicker(float secs)
{
	if(secs == 0.0f)
	{
		flickerSprite.setColor(sf::Color(255, 255, 255, 0));		// Turn the torch down/off
	}

	int flicker;

	flicker = 0 + (std::rand() % (int)(0 + (secs * 100) - 0 + 1));		// Randomise the colour value for the alpha between 0 and 255

	int number = 0 + (std::rand() % (int)(200 - 0 + 1));		// Random number to decide whether or not to bother flickering

	if(number > (200 - (secs * 10)))		// Increase/decrease this number to make flickering less/more common
	{
		flickerSprite.setColor(sf::Color(255, 255, 255, flicker));		// Turn the torch down/off
	}

	if(secs >= 2.0f)		// If the torch has flickered enough
	{
		flickerSprite.setColor(sf::Color(255, 255, 255, 255));		// Turn the torch back on
		hidden = true;
	}
}

bool CodeBox::isHidden()
{
	return hidden;
}